class AccountController < ApplicationController
    
  def start
    if session[:user_id]      
      redirect_to :action=>:home
    end
  end
  
  def signup
    if request.post?
      @user = User.new(params[:user])
      email=Email.new(:email=>params[:user][:email],:is_major=>1)
      @user.emails<<email
      @user.email=email.email
      if @user.save
        flash[:notice]=info(0,"You have successfully registered")
        AccountMailer.deliver_welcome(@user)
        session[:user_id]=@user.id
        redirect_to :action=>:home
      end      
    end    
  end
  
  def home
  end
  
  def reset
    if request.post?
      password=params[:password]
      @user.password=password
      @user.save
    else
      token=params[:token]
      @user=User.find_by_reset_hash(token)
         
      if @user.nil?
        redirect_to :action=>:signup
      else
        if @user.email=params[:email]
          session[:uid]=@user.id
          if (Time.now-@user.reset_date)>10800
            @expired=1
          end
        end
        
      end
      
    end
    
  end
  
  
  def reset_password
    if request.post?
      email=params[:email]
      user=User.find_by_email(email)
      if user.nil?
        redirect_to :action=>:signup
      else
        string_to_hash=user.hashed_password+"GruTalk"+user.object_id.to_s+rand.to_s
        user.reset_hash=Digest::SHA1.hexdigest(string_to_hash)
        user.reset_date=Time.now
        user.save
        email=AccountMailer.deliver_resetpassword(user,user.reset_hash)
        redirect_to :action=>:signin
      end
    else
      
    end
    
  end

  def remove
    user=User.find_by_username(params[:username])
    if user.id==session[:user_id]   
      user.destroy
      flash[:notice]=info(0,"You've permanently deleted your account.")
      session[:user_id]=nil
    end
      redirect_to :action=>'home'
  end

  
  def signin
    if request.post?
      user=User.authenticate(params[:username],params[:password])
      if user
        session[:user_id]=user.id
        flash[:notice]=info(0,"You've signed in to your account")
        redirect_to :action=>:home
      else
        flash[:notice]=info(2,"Invalide Username/Password")
      end
    end
  end
 
  def signout
    session[:user_id]=nil
    redirect_to :action=>'start'
  end
  
  def face
    @face = Face.find(params[:id])
    send_data(@face.data,
        :filename => @face.filename,
        :type => @face.content_type,
        :disposition => "inline" )
  end  
end
